package com.hs.hlw.credit.system.business.service.impl;

import com.hs.hlw.credit.system.business.dto.ResponseDto;
import com.hs.hlw.credit.system.business.service.SubmissionBatchService;
import com.hs.hlw.credit.system.common.enumeration.*;
import com.hs.hlw.credit.system.data.mybatis.Pageable;
import com.hs.hlw.credit.system.data.primary.mapper.DataSourceMapper;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionBatchMapper;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionFormMapper;
import com.hs.hlw.credit.system.data.primary.model.*;
import com.hs.hlw.credit.system.data.util.CommonDataUtil;
import com.hs.hlw.credit.system.data.util.DbUtil;
import com.hualongdata.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * SubmissionBatchServiceImpl
 * @author zhb
 * @date 2018/11/28
 */
@Service
public class SubmissionBatchServiceImpl implements SubmissionBatchService {
    @Value("${sftp.server.sftpPath}")
    private String sftpPath;
    private @Autowired SubmissionBatchMapper submissionBatchMapper;
    private @Autowired SubmissionFormMapper submissionFormMapper;
    private @Autowired DataSourceMapper dataSourceMapper;

    /**
     * 删除批次
     * @param id
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public ResponseDto delete(Integer id) {
        SubmissionBatch batch = submissionBatchMapper.selectByPrimaryKey(id);
        if (batch == null) {
            throw new BusinessException("批次不存在");
        }
        if (!SubmissionBatchStatus.STATUS_0.code.equals(batch.getStatus())) {
            throw new BusinessException("非待处理状态，不允许删除");
        }

        // 获取表单信息
        SubmissionForm form = checkSubmissionForm(batch.getFormId());

        // 获取数据源信息
        DataSource dataSource = checkDataSource(form.getDataSourceId());

        // 删除批次信息
        submissionBatchMapper.deleteByPrimaryKey(id);

        // 删除批次相关的数据
        DbUtil dbUtil = CommonDataUtil.getDbUtilInstance(dataSource);
        List<SubmissionFormField> whereList = new ArrayList<>();
        SubmissionFormField field = new SubmissionFormField();
        whereList.add(field);
        field.setFieldCode("ADD_BATCH_ID");
        field.setFieldValue(batch.getId().toString());
        field.setFieldDataType("VARCHAR");
        field.setLogicOperator(LogicOperator.CASE_1.code);
        dbUtil.delete(form.getTableName(), whereList);


        return new ResponseDto("删除成功");
    }

    /**
     * 批次文件下载
     * @param id
     * @return
     */
    public void downloadBatchFile(Integer id, HttpServletResponse response) {
        SubmissionBatch batch = submissionBatchMapper.selectByPrimaryKey(id);
        if (batch == null) {
            throw new BusinessException("批次不存在");
        }

        String fileName = batch.getSaveFileName();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(batch.getUploadFileName(), "UTF-8"));

            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(sftpPath + "/" + batch.getSavePath() + "/" + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            // TODO
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO
                }
            }
        }
    }

    /**
     * 分页查询报送批次
     * @param pageable
     * @return
     */
    public ResponseDto page(Pageable pageable) {
        List<SubmissionBatch> list = submissionBatchMapper.page(pageable);
        return new ResponseDto("查询成功", pageable, list);
    }

    /**
     * 校验表单
     *
     * @param formId
     */
    private SubmissionForm checkSubmissionForm(Integer formId) {
        SubmissionForm form = submissionFormMapper.selectByPrimaryKey(formId);
        if (form == null) {
            throw new BusinessException("表单不在存");
        }
        if (FormStatus.STATUS_0.code.equals(form.getStatus())) {
            throw new BusinessException("该报送功能正在升级维护，请稍后再试");
        }
        return form;
    }

    /**
     * 校验数据源
     *
     * @param dataSourceId
     */
    private DataSource checkDataSource(Integer dataSourceId) {
        DataSource dataSource = dataSourceMapper.selectByPrimaryKey(dataSourceId);
        if (dataSource == null) {
            throw new BusinessException("关联数据源不存在");
        }
        if (!CommonStatus.STATUS_1.code.equals(dataSource.getStatus())) {
            throw new BusinessException("关联数据源无效");
        }
        DataBaseType dataBaseType = DataBaseType.getDataBaseTypeByCode(dataSource.getDatabaseType());
        if (dataBaseType == null) {
            throw new BusinessException("未知的数据源类型");
        }
        if (!DataBaseType.TYPE_2.code.equals(dataSource.getDatabaseType())) {
            throw new BusinessException("暂时不支持" + dataBaseType.value + "数据库");
        }

        return dataSource;
    }
}